package com.jimmyc.fall12.OpenClass;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.http.client.ClientProtocolException;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

public class ScanService extends Service {

private List <String> mScanSites;
MyApplication mApplication; 
//for generating our timer
private Timer m_timer;
private TimerTask m_task;
private Handler m_handler;
private boolean timerOn;
	

//constants used for determining if a class is open
private final static int NOT_FOUND = -1;
private final static String OPEN = "opengreen";
private final static String WAITLIST = "waitpurple";
private final static String CLOSED = "closedred";


private String TAG = "ScanService";
	//Used for either clients (activities to access
	public class ServiceBinder extends Binder {
		ScanService getService() {
			return ScanService.this;
		}
		
	}

	private final IBinder mBinder = new ServiceBinder();


	
	
	@Override
	public IBinder onBind(Intent intent) {
		
		return mBinder;
	}
	
	
	
	//Called only once during a call to startService()
	@Override
    public void onCreate() {
       
		super.onCreate();
		 //Allow us to access global variables and functions
        mApplication = (MyApplication) getApplicationContext();
        
		mScanSites = new ArrayList <String> (3); //maximum of 3 running at a given time
		timerOn = false;
		
		
		Log.i(TAG, "Inside Service...Service Started.. ");
    }
	
	@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "Received start id " + startId + ": " + intent);
        
        // We want this service to continue running until it is explicitly
        // stopped, so return sticky.
        return START_STICKY;
    }
	 @Override
	    public void onDestroy() {
		 	//If service is ended, please stop me from running
		    if (timerOn)
		 	  m_timer.cancel();
		    Log.v(TAG, "Service Destroyed.. ");
		    super.onDestroy();
	    }

	 //functions for the interface to call
	 
	 //The application can call this function
	 public void addSite (String website) {
		
		 //add up to 5 websites
		if (mScanSites.size() < 1 ) { //For now, we will only allow one site to be scanned
			mScanSites.add(website);
			Log.v(TAG, "Website has been added");
		
		}
		else {
			Toast.makeText(this, "Can't scan any more websites", Toast.LENGTH_LONG).show();
			
		}
		// timer needs to be started only during first time of adding
		if (mScanSites.size() == 1  &&  !timerOn) {
			 timerOn = true;
			 m_timer = new Timer();
			 m_handler = new Handler();
			Log.v(TAG, "Inside timer task");
			m_task = new TimerTask() {
				String document;
				boolean open, waitList = false;
				@Override
				public void run() {
					
					m_handler.post(new Runnable() {
						public void run() {
						
							for (String site : mScanSites ) {
							
								document = mApplication.readWebpage(site); 
								if (!document.equals("")) {//ensure we got something useful 
								if (document.indexOf(OPEN) != NOT_FOUND) { //first find out whether it's open
									open = true;
									notifyUser(site);
									Log.v(TAG, "Open class: " +site);
									
								} else if (document.indexOf(WAITLIST) != NOT_FOUND) { //is there a waitlist spot?
									
									waitList = true;
									notifyUser(site);
									Log.v(TAG, "WaitList class: " +site);
								} else { //it's closed ... :(
									open = false;
									waitList = false;
								}
							}
								
							}
							

						}

						

					});
				}

			};
			
			m_timer.schedule(m_task, 0, (60 * 1000));// execute once every 1 minute
			
			
		}
	
		
		 
	 }
	 //remove website from search query
	 public boolean removeSite (String website) {
		 if (mScanSites.contains(website)) {
			 mScanSites.remove(website);
		 	 return true;
		 }
		 return false;
	 }
	 
	 private void notifyUser(String website) {
		 
			AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			MediaPlayer player = MediaPlayer.create(this,
					Settings.System.DEFAULT_NOTIFICATION_URI);
			/*
			player.setLooping(false); // Set looping to be false

			MediaPlayer player_error = MediaPlayer.create(this,
					R.raw.beep);
			player.setLooping(false); // Set looping to be false
			*/
			switch (am.getRingerMode()) {
			case AudioManager.RINGER_MODE_SILENT:
			case AudioManager.RINGER_MODE_VIBRATE:
				// Vibrate for 300 milliseconds
				v.vibrate(300);
				
				break;
			case AudioManager.RINGER_MODE_NORMAL:
				//Simple way to play a sound
				Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
				Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
				r.play();
				
				break;
			}
			Toast.makeText(this, "Class opening at.."+ website, Toast.LENGTH_SHORT).show();
			
		}
}
